extends Node

var _headTextureDic={}
var _headUrlDic={}
var _headStateDic={} #key:uid  value 不存在,未加载    1获取url中  2获取到了url  3加载中 4成功   0失败 不会重新加载

func start():
	pass
func loadHead(uid):
	if _headStateDic.has(uid):
		if _headStateDic[uid]==2: #有url 直接获取头像
			_request_head_image(uid)
			pass
	else: #获取头像url
		_headStateDic[uid]=1
		var http=HTTPRequest.new()
		add_child(http)
		http.connect('request_completed',self,'_on_request_url_completed',[http,uid],CONNECT_DEFERRED)
		var url='https://tenapi.cn/bilibili/?uid='+str(uid)
		http.request(url)
func _on_request_url_completed(result,response_code,headers,body,http,uid):
	http.queue_free()
	_headStateDic[uid]=2
	var json = parse_json(body.get_string_from_utf8())
	if json!=null && json.code==200 && json.data!=null:
		_headUrlDic[uid]=json.data.avatar
		_request_head_image(uid)
	else:
		_headStateDic[uid]=0
func _request_head_image(uid):
	_headStateDic[uid]=3
	var url=null
	if _headUrlDic.has(uid):
		url=_headUrlDic[uid]
	if url==null:
		_headStateDic[uid]=0
		return
	#确定格式
	var fomat=''
	if url.ends_with('jpg'):
		fomat='jpg'
	elif url.ends_with('png'):
		fomat='png'
	elif url.ends_with('gif'):
		fomat='gif'
	if fomat=='jpg' || fomat=='png' :
		var http=HTTPRequest.new()
		add_child(http)
		http.connect('request_completed',self,'_on_request_image_completed',[http,uid,fomat],CONNECT_DEFERRED)
		http.request(url)
	else:
		_request_otherFormat(url,uid)
	
func _on_request_image_completed(result,response_code,headers,body,http,uid,fomat):
	http.queue_free()
	var image=Image.new()
	var err
	if fomat=='jpg':
		err=image.load_jpg_from_buffer(body)
	elif fomat=='png':
		err=image.load_png_from_buffer(body)
	if err!=0:
		print('error,load Image fail')
		_headStateDic[uid]=0
	else:
		var texture=ImageTexture.new()
		texture.create_from_image(image)
		_headTextureDic[uid]=texture
		_headStateDic[uid]=4


func _request_otherFormat(url,uid):
#
	var http=HTTPRequest.new()
	add_child(http)
	http.connect('request_completed',self,'_other_format_back',[http,uid],CONNECT_DEFERRED)
	http.request('http://localhost:4000/gif2jpg/?url='+url)
	
	pass
func _other_format_back(result,response_code,headers,body,http,uid):
	http.queue_free()
	var image=Image.new()
	var buffer=body
	var err=image.load_jpg_from_buffer(buffer)
	if err!=0:
		print('error,load Image fail')
		_headStateDic[uid]=0
	else:
		var texture=ImageTexture.new()
		texture.create_from_image(image)
		_headTextureDic[uid]=texture
		_headStateDic[uid]=4
func getHead(uid):
	if _headStateDic.has(uid) && _headStateDic[uid]==4 && _headTextureDic.has(uid):
		return _headTextureDic[uid]
	return null
